package com.suian.spring.thread;

import java.util.HashMap;

/**
 * threadLocal如何实现多线程访问同一个变量
 */
public class T9ThreadLocal {
    private static ThreadLocal<HashMap<Integer, String>> threadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1, "ws");
        hashMap.put(2, "wangs");
        threadLocal.set(hashMap);
        // 线程 1
        new Thread(() -> {
//            threadLocal.set("Thread-1 Value");
//            threadLocal.set("Thread-1 Value22");
            System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get()); // 输出 Thread-1 Value
            threadLocal.remove(); // 清理
        }).start();

        // 线程 2
        new Thread(() -> {
//            threadLocal.set("Thread-2 Value");
            System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get()); // 输出 Thread-2 Value
            threadLocal.remove();
        }).start();

        System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get()); // 输出 Thread-1 Value
    }
}
